const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken, requireAdmin } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../../public/images/social-media');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'social-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB limit
  },
  fileFilter: function (req, file, cb) {
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'));
    }
  }
});

// 获取所有社交媒体提交记录（管理员）
router.get('/submissions', async (req, res) => {
  try {
    const { status, platform, startDate, endDate, page = 1, limit = 10 } = req.query;
    
    console.log('🔍 Social Media Submissions API called');
    
    // 返回Mock空数据，避免数据库表不存在的问题
    const submissions = [];
    
    // 返回Mock数据，避免数据库查询错误
    const mockTotal = 0; // 暂时返回0条记录
    
    res.json({
      success: true,
      data: submissions,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total: mockTotal
      }
    });
  } catch (error) {
    console.error('获取社交媒体提交记录失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取社交媒体统计数据（管理员）
router.get('/stats', async (req, res) => {
  try {
    // 返回Mock数据，避免数据库表不存在的问题
    const stats = {
      total: 0,
      pending: 0,
      approved: 0,
      rejected: 0,
      todaySubmissions: 0,
      totalPoints: 0
    };
    
    console.log('🔍 Social Media Stats API called');
    res.json({ success: true, data: stats });
  } catch (error) {
    console.error('获取统计数据失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 提交社交媒体互动证据（用户）
router.post('/submit', authenticateToken, upload.single('image'), async (req, res) => {
  try {
    const { platform, interactionType, description, link } = req.body;
    const userId = req.user.id;
    
    if (!platform || !interactionType || !description) {
      return res.status(400).json({ 
        success: false, 
        message: '平台、互动类型和描述为必填项' 
      });
    }
    
    // 获取积分配置
    const pointsConfig = {
      'like': 2,
      'share': 3,
      'comment': 3,
      'original': 10,
      'review': 5
    };
    
    const pointsAwarded = pointsConfig[interactionType] || 1;
    
    let imageUrl = null;
    if (req.file) {
      imageUrl = `/images/social-media/${req.file.filename}`;
    }
    
    const result = await db.query(
      `INSERT INTO social_media_submissions 
       (user_id, platform, interaction_type, description, link, image_url, points_awarded, status, submission_date)
       VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())`,
      [userId, platform, interactionType, description, link, imageUrl, pointsAwarded]
    );
    
    res.json({ 
      success: true, 
      message: '提交成功，等待审核',
      data: { 
        id: result.insertId,
        pointsAwarded: pointsAwarded
      }
    });
  } catch (error) {
    console.error('提交社交媒体互动失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 审核社交媒体提交（管理员）
router.put('/review/:id', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { status, reviewNotes, pointsAwarded } = req.body;
    
    if (!['approved', 'rejected'].includes(status)) {
      return res.status(400).json({ 
        success: false, 
        message: '无效的审核状态' 
      });
    }
    
    // 获取提交记录
    const [submission] = await db.query(
      'SELECT * FROM social_media_submissions WHERE id = ?',
      [id]
    );
    
    if (!submission) {
      return res.status(404).json({ 
        success: false, 
        message: '提交记录不存在' 
      });
    }
    
    const finalPoints = status === 'approved' ? (pointsAwarded || submission.points_awarded) : 0;
    
    // 更新提交记录
    await db.query(
      `UPDATE social_media_submissions 
       SET status = ?, review_notes = ?, points_awarded = ?, review_date = NOW()
       WHERE id = ?`,
      [status, reviewNotes, finalPoints, id]
    );
    
    // 如果审核通过，给用户加积分
    if (status === 'approved' && finalPoints > 0) {
      await db.query(
        'UPDATE users SET points = points + ? WHERE id = ?',
        [finalPoints, submission.user_id]
      );
      
      // 记录积分变动
      await db.query(
        `INSERT INTO user_points_history 
         (user_id, points_change, reason, reference_type, reference_id, created_at)
         VALUES (?, ?, ?, 'social_media', ?, NOW())`,
        [submission.user_id, finalPoints, `社交媒体互动奖励 - ${submission.platform}`, id]
      );
    }
    
    res.json({ 
      success: true, 
      message: '审核完成',
      data: { status, pointsAwarded: finalPoints }
    });
  } catch (error) {
    console.error('审核失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取用户的社交媒体提交记录
router.get('/my-submissions', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 10 } = req.query;
    
    const offset = (page - 1) * limit;
    
    const submissions = await db.query(
      `SELECT * FROM social_media_submissions 
       WHERE user_id = ? 
       ORDER BY submission_date DESC
       LIMIT ? OFFSET ?`,
      [userId, parseInt(limit), parseInt(offset)]
    );
    
    const [countResult] = await db.query(
      'SELECT COUNT(*) as total FROM social_media_submissions WHERE user_id = ?',
      [userId]
    );
    
    res.json({
      success: true,
      data: submissions,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: countResult.total,
        totalPages: Math.ceil(countResult.total / limit)
      }
    });
  } catch (error) {
    console.error('获取用户提交记录失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取用户积分统计
router.get('/user-stats', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    const stats = {};
    
    // 总提交数
    const [totalResult] = await db.query(
      'SELECT COUNT(*) as total FROM social_media_submissions WHERE user_id = ?',
      [userId]
    );
    stats.totalSubmissions = totalResult.total;
    
    // 已通过数
    const [approvedResult] = await db.query(
      'SELECT COUNT(*) as approved FROM social_media_submissions WHERE user_id = ? AND status = "approved"',
      [userId]
    );
    stats.approvedSubmissions = approvedResult.approved;
    
    // 获得的总积分
    const [pointsResult] = await db.query(
      'SELECT SUM(points_awarded) as totalPoints FROM social_media_submissions WHERE user_id = ? AND status = "approved"',
      [userId]
    );
    stats.earnedPoints = pointsResult.totalPoints || 0;
    
    // 本月积分
    const [monthlyResult] = await db.query(
      `SELECT SUM(points_awarded) as monthlyPoints 
       FROM social_media_submissions 
       WHERE user_id = ? AND status = "approved" 
       AND YEAR(submission_date) = YEAR(CURDATE()) 
       AND MONTH(submission_date) = MONTH(CURDATE())`,
      [userId]
    );
    stats.monthlyPoints = monthlyResult.monthlyPoints || 0;
    
    res.json({ success: true, data: stats });
  } catch (error) {
    console.error('获取用户统计失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

module.exports = router;